package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.Spu;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryService;
import com.leyou.item.service.SkuService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {
    @Autowired
    private SkuService skuService;
    @Autowired
    private  BrandService brandService;
    @Autowired
    private  CategoryService categoryService;
    /**
     * 分页查询商品
     * @param page     当前页
     * @param rows     每页大小
     * @param saleable 上架商品或下降商品
     * @param brandId 品牌id
     * @param categoryId 分类id
     * @param id  spu的id
     * @return
     */
    @Override
    public PageDTO<SpuDTO> querySpuByPage(Integer page, Integer rows, Boolean saleable, Long categoryId, Long brandId, Long id) {
        //TODO 层层递进
        //(最烦的是别人没写注解和自己写注解)
        //先构建分页条件(Page是IPage的实现类)
        IPage<Spu> spuIPage=new Page<>(page,rows);
        //按条件分页查询
         page(spuIPage, new QueryWrapper<Spu>()
                .eq(saleable != null, "saleable", saleable)
                .eq(categoryId != null, "cid3", categoryId)
                .eq(brandId != null, "brandId", brandId)
                .eq(id != null, "id", id)
        );
        //转成DTO
        List<SpuDTO> spuDTOS = SpuDTO.convertEntityList(spuIPage.getRecords());

        spuDTOS.forEach(spuDTO -> {
           //根据分类ID集合查询分类集合 ,并获得分类名称,以分隔符分割分类名称
            String categoryNames = this.categoryService.listCategoryByIds(spuDTO.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/")
                    );
            //设置分类名称
            spuDTO.setCategoryName(categoryNames);
            //根据品牌ID查询对应的品牌对象,并设置品牌名称
            spuDTO.setBrandName(this.brandService.queryBrandById(brandId).getName());
        });


        return new PageDTO<>(spuIPage.getTotal(),spuIPage.getPages(),spuDTOS);

    }


   //根据ID查询商品
    @Override
    public SpuDTO querySpuById(Long id) {
        Spu byId = this.getById(id);
        return new SpuDTO(byId);
    }

}
